package com.pingba.executor;

import com.pingba.entity.User;
import com.pingba.entity.friend.FriendApply;
import com.pingba.entity.msg.MsgApply;
import com.pingba.entity.msg.MsgReply;
import com.pingba.entity.msg.MsgSend;
import com.pingba.service.friend.FriendApplyService;
import com.pingba.service.msg.MsgApplyService;
import com.pingba.service.msg.MsgReplyService;
import com.pingba.service.msg.MsgSendService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/11/8 0008.
 */
@Component
public class Station {
    @Autowired
    private MsgSendService msgSendService;
    @Autowired
    private MsgReplyService msgReplyService;
    @Autowired
    private FriendApplyService friendApplyService;
    @Autowired
    private MsgApplyService msgApplyService;

    public static final String UnhandleFriendApplyKey = "FRIEND_APPLY_KEY";
    public static final String UnhandleMsgSendReplyKey = "MSG_SEND_KEY";
    public static final String UnhandleMsgReplyReplyKey = "MSG_REPLY_KEY";
    public static final String UnhandleMsgApplyKey = "MSG_APPLY_KEY";
//    public static final String UnhandleSLKey = "MSG_SL_KEY";
    private MsgCache cache = MsgCache.getCache();
    private static Logger logger = Logger.getLogger(Station.class);
//    LinkedHashMap

    private static Station station;

    private Station() {

    }

    public static Station getStation() {
        if (station == null) {
            station = new Station();
        }
        return station;
    }


    /**
     * 设置缓存中回复的消息有回复
     * @param userId
     * @param reply
     */
    private void setCacheReplyMsgReplied(long userId, MsgReply reply) {
        Map<String,List> msgInfoMap = cache.get(userId);
        if (msgInfoMap != null) {
            msgInfoMap.get(UnhandleMsgReplyReplyKey).add(reply);
        }
    }

    /**
     * 设置缓存中初始的消息有回复
     * 如果缓存中没有就不增加，为了不在缓存中缺少数据，下一次直接在缓存中拿取
     * @param userId
     * @param send
     */
    private void setCacheSendMsgReplied(long userId, MsgSend send) {
        Map<String,List> msgInfoMap = cache.get(userId);
        if (msgInfoMap != null) {
            msgInfoMap.get(UnhandleMsgSendReplyKey).add(send);
        }
    }


    /**
     * 有消息回复，更新数据库和缓存中有新消息回复
     * @param msgReply
     */
    public void msgReply(MsgReply msgReply) {
        long originalId = msgReply.getMsgId();
        System.out.println("originalId is: " + originalId);
        if (msgSendService == null) {
//            System.out.println("!!!!!!!!");
            logger.error("Spring Initial Error: Can't Autowired MsgSendService");
            return;
        }
        MsgSend original = msgSendService.selectById(originalId);
        original.setHaveResponse(true);
        msgSendService.setReplied(original);
        setCacheSendMsgReplied(original.getUserId(), original);

        long replyId = msgReply.getReplyedId();
        if (replyId == 0) {
            return;
        }
        MsgReply reply = msgReplyService.selectById(replyId);
        reply.setHaveResponse(true);
        msgReplyService.setReplied(reply);
        setCacheReplyMsgReplied(reply.getUserId(), reply);

    }

    /**
     * 在缓冲中删除，并且更新数据库
     * @param msgReply
     */
    public void msgRead(MsgReply msgReply) {
        msgReplyService.setReaded(msgReply);
        Map<String, List> listMap = cache.get(msgReply.getUserId());
        if (listMap == null || listMap.size() == 0) {
            logger.info("there is no record in cache of msgReply: " + msgReply.getSid());
            return;
        }
        List list = listMap.get(UnhandleMsgReplyReplyKey);
        if (list == null || list.size() == 0) {
            logger.info("there is no record in cahce");
            return;
        }
        list.remove(msgReply);

    }

    /**
     * 在缓存中删除，并且更新数据库
     * @param msgSend
     */
    public void msgRead(MsgSend msgSend) {
        msgSendService.setReaded(msgSend);
        Map<String, List> listMap = cache.get(msgSend.getUserId());
        if (listMap == null || listMap.size() == 0) {
            logger.info("there is no record in cache of msgReply: " + msgSend.getSid());
            return;
        }
        List list = listMap.get(UnhandleMsgSendReplyKey);
        if (list == null || list.size() == 0) {
            logger.info("there is no record in cahce");
            return;
        }
        list.remove(msgSend);
    }

    public void readMsgApply(User user) {
        msgApplyService.setReaded(user);
        Map<String, List> listMap = cache.get(user.getSid());
        if (listMap == null || listMap.size() == 0) {
            logger.info("there is no record in cache of user: " + user.getSid());
            return;
        }
        List list = listMap.get(UnhandleMsgApplyKey);
        if (list == null || list.size() == 0) {
            logger.info("there is no record in cahce");
            return;
        }
        listMap.put(UnhandleMsgApplyKey, new ArrayList<MsgApply>());
    }


    /**
     * 返回用户所有未处理的消息，也就是小圆点
     * @param user
     * @return
     */
    public  Map<String, List> getUserMsgInfo(User user) {
        long userId = user.getSid();
        Map<String, List> userMsgInfo = cache.get(userId);
        if (userMsgInfo == null) {
            userMsgInfo = initalUserMsgFromDB(user);
            cache.put(userId, userMsgInfo);
        }
        return userMsgInfo;
    }


    /**
     * 内存中没有数据，从db中初始化信息
     * 1：未处理的好友申请
     * 2：未处理的msgSend回复
     * 3：未处理的msgReply回复
     * 4：未处理的留言回复(待定)
     * 如果没有数据，不会为null，只会为空
     * @param user
     * @return
     */
    private Map<String,List> initalUserMsgFromDB(User user) {
        Map<String,List> msgInfo = new HashMap<String, List>();
        List<FriendApply> unhandleFriendApplyList = friendApplyService.getMyUnhandled(user.getSid());
        msgInfo.put(UnhandleFriendApplyKey, unhandleFriendApplyList);
        List<MsgSend> unhandleMsgSendList = msgSendService.getUnhandled(user.getSid());
        msgInfo.put(UnhandleMsgSendReplyKey, unhandleMsgSendList);
        List<MsgReply> unhandleMsgReplyList = msgReplyService.getUnhandled(user.getSid());
        msgInfo.put(UnhandleMsgReplyReplyKey, unhandleMsgReplyList);
        List<MsgApply> unhandleMsgApplyList = msgApplyService.getUnReadList(user);
        msgInfo.put(UnhandleMsgApplyKey, unhandleMsgApplyList);
        return msgInfo;
    }
}
